<?php
namespace App\Common\Lib\Swoole\Coroutine;

use App\Common as com;
use App\Common\Lib\Swoole\Coroutine\Batch as namePool;

class Batch extends com\Lib\LibBase {

	private static int $varRunStatus_Stop = 0;

	private static int $varRunStatus_Run = 1;

	private int $nextTakeId = 1;

	private int $runStatus = 0;

	/**
	 * @var namePool\_Take[]
	 */
	private array $takePool = [];
	
	public function addTakes( \Closure $fn, int $takeNum = 1 ):array {
		$takeIds = [];
		for( $i = 0; $i < $takeNum; $i++ ){
			$takeIds[] = $this->addTake( $fn );
		}
		//
		return $takeIds;
	}

	public function addTake( \Closure $fn ):namePool\_Take {
		$takeId = $this->applyTakeId();
		$take = new namePool\_Take( $this, $takeId, $fn );
		//
		$this->takePool[ $takeId ] = $take;
		//
		return $take;
	}

	public function rmTake( int $takeId ):bool {
		unset( $this->takePool[ $takeId ] );
		return true;
	}

	private function applyTakeId(  ):int {
		return $this->nextTakeId++;
	}

	public function queueLength(  ) {
		
	}

	/**
	 * @return array 返回多个执行结果
	 * @throws com\Lib\Err\BaseException\Throw_
	 * @throws com\Lib\Err\Exception
	 */
	public function runs(  ):array {
		if( $this->runStatus !== self::$varRunStatus_Stop ){
			throw com\Lib\Err\Exception::makeOfNew( '正在运行中，不可重复执行', com\Lib\Err\Code::$sysFunExecuteError );
		}
		//
		$this->runStatus = self::$varRunStatus_Run;
		//
		$runFn = [];
		foreach( $this->takePool as $takeKey => $takeValue ){
			$runFn[ $takeKey ] = function() use ( $takeValue ) {
				return $takeValue->run();
			};
		}
		$runRes = \Swoole\Coroutine\batch( $runFn );
		//
		$this->runStatus = self::$varRunStatus_Stop;
		// 返回
		return $runRes;
	}




}
